
var activeFnTag = "cust"; // 默认-个人客户 - 菜单
var activeFnIdx = 1;  // 当前按钮（默认-个人客户）
var afterMenuClickSwitchFnTag = ("menu" != activeFnTag ? activeFnTag : null); //菜单点击后需要回切的FnTag
var beforeFnTag = "cust"; // 默认前一个Fn
var fnParts = {cust: "LoginPart", group: "m_group", favo: "m_favo", notice: "m_notice", ambu: null, wiki:null,like: null, menu: "m_allmenu", config: "m_menu"};
$.sidebar = {
    init : function(){
        $("#m_fn_ul li").each(function(idx){
            $.attr(this, "idx", idx); // 设置idx属性
        });
        $("#m_fn_ul").tap($.sidebar.events.onFnTapClick);// 功能菜单点击
        $("#m_home").tap(function(){
            /*var partId = fnParts[activeFnTag];
            if(partId){
                $("#m_fn_ul li[idx=" + activeFnIdx + "]").removeClass("on");
                $("#" + partId).css("display", "none");
                document.documentElement.className = "s_noside";
                activeFnIdx = -1;
            }*/
            $.navtabset.switchToDefNav();
        });
        var partId = fnParts[activeFnTag]; //当前tag id
        $("#m_fn_ul li[idx=" + activeFnIdx + "]").addClass("on");
        $("#" + partId).css("display", ""); //功能按钮 对应 菜单
        $(document.documentElement).removeClass("s_noside");
    },
    checkStaffPwd: function(){
        setTimeout(function(){
            $.ajax.submit(null,"checkStaffPwd", null, null, function(data){
                if(data && data.get("REMINDER_TAG")=="1"){
                    var info = data.get("RESULT_MSG");
                    if(info < 10){
                        $.MessageBox.confirm("提示","距密码过期还有"+info+"天，请及时修改密码！",function(re){
                            if(re=="ok"){
                                //$.menuopener.openMenu("", "员工密码自助重置", "/commonbusinesscentre/commonbusinesscentre?service=page/secframe.bs.securitymgt.SafetyQuestionMgt&listener=init");
                            }
                        });
                    }
                }
            }, function(error_code,error_info,detail){
                $.MessageBox.error(error_info);
            });
        },2000);
    },
    navAction: function(){
        $('#helpNavPerson').css('display','none');
        $('#helpNavGroup').css('display','none');
        $.ajax.submit(null, "tipAction", "&operType=0", null, null, null);
    },
    msgAction: function(){
        $('#UI-release').css('display','none');
        if($('#msgnoshow').attr('checked')){
            $.ajax.submit(null, "tipAction", "&operType=1", null, null, null);
        }
    },
    tipAction: function(content){
        $('#searchTipContent').text(content);
        $('#searchTip').css('display','');
        setTimeout(function(){
            $('#searchTip').css('display','none');
        },5000);
    },
    //无法获取准确数据,屏蔽此功能
    /*	fetchFee:function(t){

            setTimeout(function(){
                $.ajax.submit(null,"fetchFee", null, null, function(data){
                    $("#monFee").text(data.get("MONTH_TOTAL"));
                    $("#dayFee").text(data.get("DAY_TOTAL"));
                }, function(error_code,error_info,detail){
                    //$.MessageBox.error("获取营业员收费信息", error_info,null,null,detail);
                });

            },t);
        },*/
    //删除收藏菜单
    deleteCollect: function(e,favId){

        ajaxSubmit(null,'deleteCollect','&favId='+favId,null,
            function(){
                $(e).parent().remove();
            },
            function(error_code,error_info,detail){
                MessageBox.error('错误信息',error_info);
            });
    },
    // 刷新收藏夹
    freshFavMenu: function(){
        ajaxSubmit(null, 'getCollectMenu', null, 'favo_pages', function(){
            var idx = $("#favo_tabs li[class=on]").attr("idx");
            $($("#favo_pages").children()[0]).css("display","none");
            $($("#favo_pages").children()[idx]).css("display","");
        },function(error_code,error_info,detail){
            $.MessageBox.error("获取数据失败", error_info,null,null,detail);
        });
    },
    events : {
        onFnTapClick: function(e){
            var el = e.target;

            if(!el || !el.nodeType || !$.nodeName(el, "li"))
                return;

            var tag = $.attr(el, "tag");
            var idx = $.attr(el, "idx");
            beforeFnTag = activeFnTag; //将切换前的FnTag设置为之前的FnTag
            var partId = fnParts[activeFnTag]; // 对应功能页id
            if(idx == activeFnIdx) { // 重复点击
                $("#m_fn_ul li[idx=" + activeFnIdx + "]").removeClass("on");
                $("#" + partId).css("display", "none"); // 对应功能页隐藏
                $(document.documentElement).addClass("s_noside");
                activeFnIdx = -1;
                return;
            }
            //费用组件切换
            if(tag == "cust"||tag == "group"){
                if(tag=="cust"){
                    var innerHtmlStr= $("#personFee").html();
                    if(innerHtmlStr.indexOf("fee")<=0){
                        var feeHtmlStr=$("#groupFee").html();
                        $("#personFee").html(feeHtmlStr);
                        $("#groupFee").html("");
                    }
                }
                if(tag=="group"){
                    var innerHtmlStr= $("#groupFee").html();
                    if(innerHtmlStr.indexOf("fee")<=0){
                        var feeHtmlStr=$("#personFee").html();
                        $("#groupFee").html(feeHtmlStr);
                        $("#personFee").html("");

                    }
                }
            }

            if(tag == "like"){
                openNav("给设计师点赞", "bs.config.likeAPerson", "init", "", "/resourcecentre/resourcecentre");
            }
            if(tag == "wiki"){
                //window.open("http://10.173.226.172:8081/csp/c_kbs/oAoutLink.action?staffId=ZKF11353","newwindow","height=600,width=800,top=0,left=0");

                //$.menuopener.openMenu("", '知识库首页', 'http://10.200.151.43:8080/knowledgebase/hissologin/hissologin!hikfLogin.do', 'help');
                //$.menuopener.openMenu("ZHS1100", '知识库首页', '/knowledgebase/ssologin!NGBOSSLogin.do?menu=11', '知识库首页');
                //修改点：上线前，需要换成生产环境的url
                //$.menuopener.openMenu("ZHS1100", '知识库首页', 'http://10.200.138.24/knowledgebase/hissologin/hissologin!hikfLogin.do', 'help');
                $.menuopener.openMenu("", '知识库首页', 'http://ngboss.hi.cmcc/knowledgebase/index.jsp', 'help');
            }
            // 通知
            if(tag == "notice"){
                setTimeout(function(){
                    if(window.noticeUnreadScroller){
                        window.noticeUnreadScroller.refresh();
                    }
                    if(window.noticeReadedScroller){
                        window.noticeReadedScroller.refresh();
                    }
                }, 100);
            }

            partId = fnParts[tag];
            if(partId){
                $("#" + fnParts[activeFnTag]).css("display", "none");
                $("#" + partId).css("display", "");
                $(document.documentElement).removeClass("s_noside");
                if(partId=="m_menu") m_menu.refresh(); // 1028 xiams ?
                $("#m_fn_ul li[idx=" + activeFnIdx + "]").removeClass("on");
                $("#m_fn_ul li[idx=" + idx + "]").addClass("on");

                activeFnTag = tag;
                activeFnIdx = idx;

                //记录最后切换的非全菜单fnTag
                if( "menu" != tag ){
                    afterMenuClickSwitchFnTag = tag;
                }
            }else{
                //document.documentElement.className = "s_noside";
            }
        },
        showFn: function(tag){
            var curE = $("#m_fn_ul li[idx=" + activeFnIdx + "]");
            //var curE = $("#m_fn_ul li").eq(activeFnIdx);
            if(curE && curE.attr("tag")==tag){ // 重复点击
                return ;
            }
            var partId = fnParts[tag];
            if(curE && partId){
                curE.removeClass("on");
                $("#" + fnParts[activeFnTag]).css("display", "none");
            }
            if(partId){
                $("#m_fn_ul li[tag=" + tag + "]").addClass("on");
                $("#" + partId).css("display", "");
                $(document.documentElement).removeClass("s_noside");

                activeFnTag = tag;
                activeFnIdx = $("#m_fn_ul li[tag=" + tag + "]").attr("idx");
            }
        },
        hideFn: function(){
            var curE = $("#m_fn_ul li[idx=" + activeFnIdx + "]");
            if(curE){
                curE.removeClass("on");
                $("#" + fnParts[curE.attr("tag")]).css("display", "none");
            }
            $(document.documentElement).addClass("s_noside");
            activeFnIdx=-1;
        }
    }
};

$.shortcut = {
    init: function(){
        $("#m_shortcut li[addr]").bind("click", $.shortcut.onClick);
    },
    open: function(menuId, title, addr, path){
        //var breadNav = "快捷菜单 > " + path;
        $.menuopener.openMenu(menuId, title, addr, path);
    },
    onClick: function(e){
        var el = e.target;
        if(!el || !el.nodeType)
            return;
        if( $.nodeName(el, "span") )
            el = el.parentNode;

        var menuId = $.attr(el, "menuId");
        var title = $.attr(el, "title");
        var addr = $.attr(el, "addr");
        var path = $.attr(el, "path");

        if(!title) title = $.attr(el, "tip");
        if(title){
            title = ("" + title).split("，")[0];
        }
        $.shortcut.open(menuId, title, addr, path);
    }
};

$.activator = {
    interval: null,
    time: 10 * 60 * 1000,
    start: function(){
        if(!this.interval){
            this.interval = window.setInterval($.activator.action, this.time);
        }
    },
    stop: function(){
        if(this.interval){
            window.clearInterval(this.interval);
            this.interval = null;
        }
    },
    action: function(){
        $.httphandler.get("com.asiainfo.touchframe.view.handler.VariableHandler", "active", null, null, null, {
            simple : true,
            dataType : "text"
        });
    }
};

/*
	lockTime - 锁屏时间，单位分钟
*/
$.locktask = {
    interval: null,
    time: 20 * 1000,
    locktime: (window.frame_locktime ? window.frame_locktime : 30),
    activetime: (new Date()).valueOf(),
    start: function(){
        if(!this.interval){
            this.interval = window.setInterval($.locktask.action, this.time);
        }
    },
    stop: function(){
        if(this.interval){
            window.clearInterval(this.interval);
            this.interval = null;
        }
    },
    action: function(){
        if((new Date()).valueOf() - $.locktask.activetime > $.locktask.locktime * 60 * 1000
            && !$.lock.locked){
            //$.lock.show();
        }
    },
    update: function(){
        this.activetime = (new Date()).valueOf();
    }
};

$.lock = {
    locked: false,
    unlocking: false,
    limit: 3,
    init: function(){
        $("#UNLOCK_PASSWORD").keydown($.lock.onPassKeyDown);
        $("#UNLOCK_BTN").click($.lock.onBtnClick);
        //$.locktask.start();
        //$.lock.adjustHeight();
    },
    show: function(){
        $("#m_lock").css("display","");
        $("#UNLOCK_PASSWORD").focus();
        $.activator.start();
        $.lock.locked = true;
    },
    hide: function(){
        $.activator.stop();
        $("#m_lock").css("display","none");
        $.lock.locked = false;
    },/*
	adjustHeight: function(){
		var bh = $(document.body).height(),
		    hh = $("#m_header").attr("offsetHeight")
		    nh = $("#m_nav").attr("offsetHeight"),
		    th = $("#m_task").attr("offsetHeight"),
		    sh = $("#m_sidetab").attr("offsetHeight");

		var h = bh - hh - nh - th;
		var h1 = h - sh;
		$("#main_ct").css("height", h + "px");
		$("#side_ct").css("height", h1 + "px");
		$("#right_pushinfo").css("height", h + "px");
	},*/
    onPassKeyDown: function(e){
        //回车键
        if(e.keyCode == 13 || e.keyCode == 108){
            $("#UNLOCK_BTN").trigger("click");
            return false;
        }
    },
    onBtnClick: function(e){
        if($.lock.unlocking)return;
        if($.lock.limit <= 0){
            alert("已经达到了最大解锁重试次数，请重新登录！");
            //强制退出
            logout();
            return;
        }
        var pass = $("#UNLOCK_PASSWORD").val();
        if(!pass){
            alert("密码不能为空！");
            $("#UNLOCK_PASSWORD").focus();
            return;
        }
        $("#UNLOCK_PASSWORD").attr("disabled",true);
        $("#lock_tip").text("正在校验密码...");
        $.lock.unlocking = true;
        $.ajax.submit(null, "unLock", "UNLOCK_PASSWORD=" + $.md5($.md5_3($.fnEncrypt(pass,"00linkage"))), null, function(data){

            enc=data.get("UNLOCK_RETRUN_ENC");
            enp= $.md5($.md5_3("0"+$.md5($.md5_3($.fnEncrypt(pass,"00linkage")))));

            if(enc != null && enc == enp ){
                $.lock.unlocking = false;
                $("#UNLOCK_PASSWORD").val("");
                $("#UNLOCK_PASSWORD").attr("disabled","");
                $("#lock_tip").text("注意：您最多只能尝试解锁3次");
                $.locktask.update(); //update locktask
                $.lock.limit = 3;
                $.lock.hide();

            }else{
                $.lock.unlocking = false;
                if($.lock.limit > 0) $.lock.limit --;

                $("#UNLOCK_PASSWORD").attr("disabled","");
                $("#lock_tip").text("您还可以尝试解锁" + $.lock.limit + "次");
                $("#UNLOCK_PASSWORD").select();

                $("#UNLOCK_PASSWORD").val("");
                $("#UNLOCK_PASSWORD").attr("disabled",true);
                $.activator.stop();
                logout();

            }

        }, function(code, info){
            $.lock.unlocking = false;
            if($.lock.limit > 0) $.lock.limit --;
            alert(info);

            $("#UNLOCK_PASSWORD").attr("disabled","");
            $("#lock_tip").text("您还可以尝试解锁" + $.lock.limit + "次");
            $("#UNLOCK_PASSWORD").select();

            if("登录已过期，请重新登录！" == info
                || "已经达到了最大解锁重试次数，请重新登录！" == info){
                $("#UNLOCK_PASSWORD").val("");
                $("#UNLOCK_PASSWORD").attr("disabled",true);
                $("#lock_tip").text(info);
                $.activator.stop();
                //强制退出
                logout();
            }
        });
    }
}

$.staffcheck = {
    interval: null,
    time: 5 * 1000,
    activetime: (new Date()).valueOf(),
    start: function(){
        if(!this.interval){
            this.interval = window.setInterval($.staffcheck.action, this.time);
        }
    },
    stop: function(){
        if(this.interval){
            window.clearInterval(this.interval);
            this.interval = null;
        }
    },
    action: function(){
        if(window.staffId){
            $.httphandler.get("com.asiainfo.touchframe.view.handler.VariableHandler", "staffCheck", "&staffId=" + window.staffId, function(data){
                if("faild" == data){
                    alert("该终端有新的工号登录NGBOSS，工号[" + window.staffId  + "]将退出登录");
                    try{
                        window.doUnloadLogout = false;
                        parent.window.opener = null;
                        parent.window.open("", "_self");
                        parent.window.close();
                    }catch(ex){
                        window.doUnloadLogout = true;
                    }
                }
            }, null, {
                simple : true,
                dataType : "text"
            });
        }
    }
};

//注销登录
var doUnloadLogout = true;
function logout(){
    //最后使用的subsys菜单
    $.ajax.get("Logout", "logout", null, null, function(){
        if(frame_isdebug){	 //开发模式 跳转
            $.redirect.toPage("Home","","");
        }else{    //否则关闭
            //alert("感谢您的使用！");
            try{
                window.doUnloadLogout = false;
                parent.window.opener = null;
                parent.window.open("", "_self");
                parent.window.close();
            }catch(ex){
                window.doUnloadLogout = true;
            }
        }
    },function(){
        try{
            window.doUnloadLogout = false;
            parent.window.opener = null;
            parent.window.open("", "_self");
            parent.window.close();
        }catch(ex){
            window.doUnloadLogout = true;
        }
    },{async: false});

}

// 退出登录
$.forceLogout = {
    doit: function(content){
        MessageBox.show({
            error : true,
            msg : "您已经被强制下线",
            content : (content ? content : "您已经被强制下线,请与系统管理人员联系"),
            buttons : {"cancel" : "关闭"},
            fn : function(btn){

            },
            beforeHide : function(btn){
                $.ajax.get("Logout", "logout", null, null, function(){
                    $.redirect.toPage("Home");
                },function(code, msg){
                    $.redirect.toPage("Home");
                },{async:false});
            }
        });
    }
};
/*
function changeCallBack(data){
	$("#city_btn").text(data.get("eparchyName"));
	$("#staff_city").text(data.get("eparchyName"));
}

function changeError(error_code,error_info,detail){
	$.MessageBox.error("切换登录地州失败", error_info,null,null,detail);
}
*/

var dateOffset = 0;
function loadDbTime(dbTime){
    if (dbTime) {
        var times = dbTime.split("-");
        var curDate = new Date();
        curDate.setMonth(times[0] - 1);
        curDate.setDate(times[1]);
        curDate.setHours(times[2]);
        curDate.setMinutes(times[3]);
        curDate.setSeconds(times[4]);
        curDate.setTime(curDate.getTime() + 500);
        dateOffset = new Date().getTime() - curDate.getTime();
        $("#mainDbTime").text(curDate.format("MM-dd(E) HH:mm:ss"));
        setInterval("loadDbTime()", 970);
    } else {
        var curDate = new Date();
        curDate.setTime(curDate.getTime() - dateOffset);
        $("#mainDbTime").text(curDate.format("MM-dd(E) HH:mm:ss"));
    }
}

function show(el, str) {
    var o;
    typeof el == "object" ? o = el : o = document.getElementById(el);
    o.style.display = "";
    if(str) {
        o.style.display = str;
    }
}

function hide(el) {
    var o;
    typeof el == "object" ? o = el : o = document.getElementById(el);
    o.style.display = "none";
}

function browserCheck(){
    //IE浏览器升级提醒
    var doCheck = true == window.doBrowserCheck, UA = navigator.userAgent;
    if( doCheck && (UA.indexOf("MSIE") > -1 || UA.indexOf("Trident") > -1)
    ) {
        var m = (/Trident\/([0-9.]+);/g) .exec(UA) ;
        if(!m || !m.length || "7.0" != m[1]) {
            var content = "您当前IE浏览器版本不是IE11，为得到更好体验，建议您将IE浏览器升级<br />点击<a href=\"/static/setup/IE11升级包.zip\" target=\"_blank\">这里</a>下载IE11升级安装程序和安装说明"
            m = (/Windows NT ([0-9.]+);/g).exec(UA);
            if(m && m.length && parseInt(m[1]) < 6){
                content += "，由于您的操作系统版本太低，您需要升级到Windows7以上的操作系统才能安装IE11";
            }
            MessageBox.show({
                "msg": "浏览器升级提示",
                "content": content,
                "confirm": true,
                "buttons": {ok: true}
            });
        }
    }
}

$(function(){

    if(!frame_isdebug && $.browser.msie){

        $(window).bind("beforeunload", function(e){
            //return; //开发时return
            if(doUnloadLogout){
                return "将注销当前用户并退出系统";
            }
            return;
        });

        $(window).unload(function(e){
            if(doUnloadLogout){
                //使用同步的ajax来注销登录
                logout(); //开发时注销该行
            }
        });
    }

    $.shortcut.init();
    $.sidebar.init();
    $.lock.init();

    if(true == window.frame_staffcheck){
        $.staffcheck.start();
    }


    // 个人信息  点击 hover
    $("#staff_min").bind("click",function(){
        $("#staff_max").css("display", "");
        //$("#city_btn").removeClass("city-unfold");
        //$("#city_choose").css("display", "none");
    });

    $("#staff_max").bind("mouseleave",function(){
        $("#staff_max").css("display", "none");
    });

    $("#more_btn").bind("click",function(){
        $("#staff_max").css("display", "none");
        $('#menu_btn').trigger('tap');
    });

    $("#exit_btn").bind("click", function(){

        MessageBox.confirm('退出提示', '确认退出吗？', function(btn){
            if( 'ok' == btn ){
                window.doUnloadLogout = false;
                logout();
            }
        });
        //logout();
    });

    $("#favo_tabs li").each(function(idx){
        $.attr(this, "idx", idx);
    });

    $("#favo_tabs li").bind("tap",function(e){
        if($(e.target).hasClass("on")){
            return ;
        }
        var oldIdx = $("#favo_tabs li[class=on]").attr("idx");
        $("#favo_tabs li[class=on]").removeClass("on");
        $(e.target).addClass("on");
        var idx = $(e.target).attr("idx");
        $($("#favo_pages").children()[oldIdx]).css("display","none");
        $($("#favo_pages").children()[idx]).css("display","");
    });

    if($("#isProv").val()=='1'){//全省工号
        /*
        $("#city_btn").bind("click",function(){
            var show = $("#city_choose").css("display");
            if(show == "none"){
                $("#city_btn").addClass("city-unfold");
                $("#city_choose").css("display", "");
            }else{
                $("#city_btn").removeClass("city-unfold");
                $("#city_choose").css("display", "none");
            }
        });

        $("#city_choose li").bind("click",function(e){
            $("#city_btn").removeClass("city-unfold");
            $("#city_choose").css("display", "none");
            var eparchyCode = $(e.target).attr("code");
            var eparchyName = $(e.target).text();
            if(eparchyCode && eparchyName){
                $.ajax.submit(null, "changeLoginEparchy", "eparchyCode=" + eparchyCode + "&eparchyName=" + encodeURIComponent(eparchyName), null, changeCallBack, changeError);
            }
        });
        */
    }
    //导入导出日志查询
    $("#my_impexp").bind("tap",function(e){
        openNav("导入导出日志", "impexp.ImpExp", "init", null,"/basecentre/basecentre");
    });
    //分布式缓存刷新
    $("#memCacheFlush").bind("tap",function(e){
        openNav("静态参数缓存", "secframe.op.flushmemcache.FlushMemCache", null,null,"/commonbusinesscentre/commonbusinesscentre");
    });

    //权限验证
    $("#privCheck").bind("tap",function(e){
        openNav("权限验证", "ngboss.priv.PrivCheckPage", "init",null,"/ngboss");
    });

    //权限刷新
    $("#privReload").bind("tap",function(e){
        openNav("权限刷新", "ngboss.priv.PrivLoadPage", "", null,"/ngboss");
    });

    //异常编码维护
    $("#errCode").bind("tap",function(e){
        openNav("异常编码维护", "secframe.op.errorcode.ErrorCode", null,null,"/commonbusinesscentre/commonbusinesscentre");
    });
    //图标选择
    $("#iconChoose").bind("tap",function(e){
        openNav("图标选择", "secframe.op.iconchoose.IconChoose", 'init','&centrecode=CommonBusinessCentre',"/commonbusinesscentre/commonbusinesscentre");
    });
    //会话管理
    $("#monitorses").bind("tap",function(e){
        openNav("会话管理", "secframe.op.monitorses.MonitorSes", null,'&centrecode=CommonBusinessCentre',"/commonbusinesscentre/commonbusinesscentre");
    });
    //会话监控
    $("#monitormap").bind("tap",function(e){
        openNav("会话监控", "secframe.op.monitorses.MonitorMap", 'init','&centrecode=CommonBusinessCentre',"/commonbusinesscentre/commonbusinesscentre");
    });
    //截屏
    $("#screenShots").bind("tap",function(){
        try{
            var ocx=new ActiveXObject("ScreenCapture.CNGSC");
            var path = ocx.GetScreenImage();
            if (path != null && path != '') {
                alert('截图文件位置:'+path);
            }
        } catch(e){
            alert('未找到截图控件，请下载完成后安装，截图控件仅支持IE11(32bit)');
            window.open('/static/printScreen.exe','_new_download_win','height=40,width=100,top=0,left=0,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');
        }
    });
    //收藏菜单显示
    $("#favoFn").bind("click",$.sidebar.freshFavMenu);

    $("#m_menu_log").bind("tap",function(){
        window.open('log.jsp','_new_log_win','height=600,width=1000,top=0,left=0,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');
    });

    if($("#isManager").val()=="1"){
        $("#groupFn").trigger("tap");
    }
    //$.sidebar.checkStaffPwd();
    //$.sidebar.fetchFee(5000);

    if($("#navShow").val() !="1" ){
        if($("#isManager").val()=="1"){
            $('#helpNavGroup').css('display','');
        }else{
            $('#helpNavPerson').css('display','');
        }
    }

    if($("#msgShow").val() != "1"){
        $('#UI-release').css('display','');
    }

    browserCheck();
});
